import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import { t } from '@lingui/macro';

export default class CcStationStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['fullId;asc'],
      size: 10,
    },
  };
  total = 0;
  _region = {}; // 选中的区域
  hotRegion = [];
  stations = [];
  loading = false;

  city = {};
  regions = {};

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false, _region: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { fullId } = this._region || {};
    _.assign(this._args.search, { fullId: fullId ? `^${fullId}` : '' });

    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;

    this.loading = true;
    try {
      this.total = yield api.count({ search });
      const stations = yield api.search({ search, pg });
      this.stations = stations.map((p) => ({
        ...p,
        disabled: !p.disabled,
        city: this.city[p.fullId.split(':')[0]],
      }));
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * _reload(cause) {
    yield this.query();
  }

  * update(station) {
    yield api.update(station);
    yield this._reload(station);
  }

  * create(station) {
    yield api.create(station);
    yield this._reload(station);
  }

  * remove(station) {
    yield api.remove(station.itemId);
    yield this._reload(station);
  }

  * updateState(station) {
    const { itemId, disabled } = station;
    yield api.update({ itemId, disabled });
    yield this.query();
  }

  * nextId(parentId) {
    return yield api.nextId(parentId);
  }

  * getHotRegion() {
    const res = yield api.getHotRegion();
    this.hotRegion = res.map((item) => ({
      label: item.name,
      value: item.name,
    }));
  }

  * allRegions(maxLevel) {
    const res = yield api.allRegions(maxLevel);
    const city = res.filter((p) => p.itemId.length === 3) || [];
    const region = res.filter((p) => p.itemId.length === 6) || [];
    this.city = city.reduce((acc, cur) => {
      const { name, itemId } = cur;
      acc[itemId] = name;
      return acc;
    }, {}) || {};
    this.regions = region?.reduce((acc, cur) => {
      const { name, itemId } = cur;
      acc[itemId] = name;
      return acc;
    }, {}) || {};
  }

  async existsValidator(rule, value) {
    if (!value) return Promise.resolve();
    try {
      const item = await api.get(value); // 注意get不存在时会抛出404异常
      if (item) return Promise.reject(new Error(t`${value}已存在`));
    } catch (_) {
      return Promise.resolve();
    }
  }

  get region() {
    return this._region;
  }

  set region(r) {
    this._region = r;
    this.query();
  }

  isDictrict() { // 当前选中区域是否行政区
    // console.log('this._region', this._region, this._region?.fullId?.indexOf(':'));
    if (!this._region?.fullId) return false;
    return this._region?.fullId?.indexOf(':') !== -1;
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
    // _.mergeWith(this._args.pg, pg, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }
}
